package com.zzh.mvvm.binding.click.observable;


import android.view.View;

import com.zzh.mvvm.binding.internal.Preconditions;
import com.zzh.rxandroid.MainThreadDisposable;

import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.Observer;

/**
 * Created by zzh on 2023/11/1.
 *
 * @date: 2023/11/1 20:47
 * @email: zzh_hz@126.com
 * @author: zzh
 * @description: com.zzh.mvvm.binding.click.observable
 */
public class ViewClickObservable extends Observable<Object> {
    private View view;

    public ViewClickObservable(View view) {
        this.view = view;
    }

    @Override
    protected void subscribeActual(@NonNull Observer<? super Object> observer) {
        if (!Preconditions.checkMainThread(observer)) {
            return;
        }
        Listener listener = new Listener(view, observer);
        observer.onSubscribe(listener);
        view.setOnClickListener(listener);
    }

    private class Listener extends MainThreadDisposable implements View.OnClickListener {

        private View view;
        private Observer<Object> observer;

        public Listener(View view, Observer<Object> observable) {
            this.view = view;
            this.observer = observable;
        }

        @Override
        public void onClick(View v) {
            if (!isDisposed()) {
                observer.onNext(v);
            }
        }

        @Override
        protected void onDispose() {
            view.setOnClickListener(null);
        }
    }
}
